<?php

class  Orders_model extends CI_Model
{
    public function __construct()
    {
        $this->load->helper("url");
        $this->load->model('assets_model');
        $this->load->model('users_model');
//        $this->load->model('jpush_model');
    }

    //提成操作
    function push_moeny_do($order_id = 0, $money = 0, $customer_id = 0, $manager_id = 0)
    {
        if ($order_id && $money && $customer_id && $manager_id) {
            //获取经理的上级
            $sql = "select bind.parent_id from manager mg INNER JOIN manager_bind bind ON mg.id = bind.manager_id WHERE  mg.id = $manager_id";
            $rs = $this->db->query($sql)->result_array();
            if ($rs) {
                $parent_id = $rs[0]['parent_id'];
                $push = [
                    'customer_id' => $customer_id,
                    'manager_id' => $parent_id,
                    'order_id' => $order_id,
                    'money' => $money,
                    'push_money' => 99,
                    'created_at' => date("Y-m-d h:i:s")];
                $string = $this->db->insert_string("push_money", $push);
//                $sql_up = "update manager set "s
                $comm_bool = $this->db->query($string);
                //查询有没有上上一级(大区经理)
                $sql = "select bind.parent_id from manager mg INNER JOIN manager_bind bind ON mg.id = bind.manager_id WHERE  mg.id = $parent_id";
                $pp_rs = $this->db->query($sql)->result_array();
                if ($pp_rs) {
                    $parent_id1 = $pp_rs[0]['parent_id'];
                    $push = [
                        'customer_id' => $customer_id,
                        'manager_id' => $parent_id1,
                        'order_id' => $order_id,
                        'money' => $money,
                        'push_money' => 99,
                        'created_at' => date("Y-m-d h:i:s")];
                    $string = $this->db->insert_string("push_money", $push);
                    $comm_bool = $this->db->query($string);
                }
            }
            //上上级

        }
    }

    //获取订单列表 add by chendm 2017-9-4
    public function getOrderList($manager_id, $finish_status = 'all', $commission_status = 0, $search = '', $limit = 3, $page = 1)
    {

        $sql = " SELECT c.id customer_id,co.order_bn,co.id order_id,co.commission_total,co.commission_status,c.customer_name,c.pic_path,co.order_date FROM customer_order co LEFT JOIN customer c ON co.customer_id=c.id  WHERE co.manager_id=$manager_id AND c.shop_customer_id>0 ";
        switch ($finish_status) {
            case '1':
                $sql .= " AND co.order_status='交易成功'";
                break;
            case '2':
                $sql .= " AND co.order_status IN ('买家已付款','卖家已发货')";
                break;
            case '3':
                $sql .= " AND co.order_status='等待买家付款'";
                break;
            case '4':
                $sql .= " AND co.order_status in ('已退货','退货中')";
                break;
            default:
                break;
        }
        switch ($commission_status) {
            case '1':
                $sql .= " AND co.commission_status='已结算'";
                break;
            default:
                $sql .= " AND co.commission_status<>'已结算'";
                break;
        }

        //按输入手机号、姓名模糊匹配查询
        if ($search) {
            $sql .= " AND (c.customer_name LIKE '%$search%' OR customer_tel LIKE '%$search%' OR co.order_bn LIKE '%$search%' )";
        }

        $sql .= " ORDER BY co.id DESC";

        $limit_from = ($page - 1) * $limit;
        $sql .= " LIMIT " . $limit_from . "," . $limit;
        $res = $this->db->query($sql)->result_array();
        foreach ($res as $v) {
            //搜索条件
            $orders[$v['customer_id']][] = $v['order_bn'];
        }
        if ($orders) {
            //获取指定多个客户的订单
            $url = $this->config->item("shop_base_url") . "citymanagerapi/get_order_info/";
            $params['key'] = md5_key();
            $params['orders'] = json_encode($orders);
            //发送数据
            $get_data = curl_request($url, $params);
            $get_data = json_decode($get_data, true);
            // echo '<pre/>';print_r($get_data);exit; 
            if ($get_data['code'] == 200) {
                $data['status'] = "success";
                $data['data'] = $get_data['data'];
                $orders = [];

                    foreach ($res as $r) {
                        foreach ($data['data'] as $v) {
                        if ($v['order_sn'] == $r['order_bn']) {
                            $v['real_name'] = $r['customer_name'];
                            $unit = array_merge($v,$r);
                            $orders[] = $unit;
                        }
                    }
                }
                $data['data'] = $orders;
            } else {
                $data['msg'] = $get_data['msg'];
                $data['status'] = "fail";
                $data['data'] = "";
            }
        } else {
            $data['status'] = "success";
            $data['data'] = "";
        }
        return $data;
    }


    public function getOrderDetail($manager_id, $order_id)
    {
        //根据订单id查询信息
        $sql = " SELECT c.id,co.customer_id as customer_id,c.shop_customer_id,c.customer_name customer_name,co.order_bn,co.commission_total,co.commission_status FROM customer_order co LEFT JOIN customer c ON co.customer_id=c.id WHERE co.manager_id=$manager_id AND co.id=$order_id ";
        $res = $this->db->query($sql)->result_array();
        if ($res) {
            $url = $this->config->item("shop_base_url") . "citymanagerapi/get_order_detail/";
            $params['key'] = md5_key();
            $params['customer_id'] = $res['0']['customer_id']; //71
            $params['order_bn'] = $res['0']['order_bn']; //0010170901040005
            //发送数据
            $get_data = curl_request($url, $params);
            $get_data = json_decode($get_data, true);
            if ($get_data['code'] == 200) {
                $data['status'] = "success";
                $data['data'] = $get_data['data'];
                $data['data']['real_name'] = $res[0]['customer_name'];
                $data['data']['customer_id'] = $res[0]['customer_id'];
            } else {
                $data['msg'] = $get_data['msg'];
                $data['status'] = "fail";
                $data['data'] = "";
            }
        } else {
            $data['msg'] = '订单不存在';
            $data['status'] = "fail";
            $data['data'] = "";
        }
        //获取指定多个客户的订单

        return $data;
    }

    function order_sync($order_sn = "", $app_customer_id = 0, $order_status = 0, $time = "", $orders = "", $returns = "",$discount=100)
    {
        if ($order_sn && $app_customer_id && isset($order_status) && $time) {
            // 推送用的信息
            $this->load->library('Jpush', '', 'mylib');
            $jpush = $this->mylib;
            $cus = $this->db->where(array("id" => $app_customer_id))->get("customer")->row_array();
            $manager_id = $cus['manager_id'];
            $customer_name = $cus['customer_name'];
            $manager_info = $this->db->where(array("id" => $manager_id))->get("manager")->row_array();
            $manager_tel = $manager_info['tel'];
            $manager_name = $manager_info['name'];
            $registration_id = $manager_info['registration_id'];
            $title_arr = array('客户下单通知', '客户退货通知', '客户付款成功通知');
            // 开启事务
            $this->db->trans_begin();
            //第一次下单
            if ($order_status == 0) {
                //下单信息
                $orders = json_decode($orders, true);
                if (!$orders || count($orders) <= 0) {
                    $data['status'] = "fail";
                    $data['msg'] = "下单订单信息不可为空";
                    $this->db->trans_rollback();
                    echo json_encode($data);
                    exit;
                }
                //根据客户id 查找销售经理id
                $mg = $this->db->where(array("id" => $app_customer_id))->get("customer")->row_array();

                // 新增折扣字段
                $order = [
                    'customer_id' => $app_customer_id,
                    'manager_id' => $mg['manager_id'],
                    'order_bn' => $order_sn,
                    'order_money' => $orders['money'],
                    'order_date' => $time,
                    'discount' => $discount
                ];
                $this->db->insert("customer_order", $order);
                $insert_id = $this->db->insert_id();
                if (!$this->db->affected_rows()) {
                    $data['status'] = "fail";
                    $data['msg'] = "订单同步失败";
                    $this->db->trans_rollback();
                    echo json_encode($data);
                    exit;
                } else {
                    $data['status'] = "success";
                    $data['msg'] = "同步成功";
                }
                //计算佣金
                $products = $orders['products'];
                //商品总数量
                $total_goods_count = 0;
                if ($products && count($products) > 0) {
                    $get_commission = 0;
                    foreach ($products as $v) {
                        if ($v['ratio'] >= 75 && $v['ratio'] <= 100) {
                            $commission = ($v['final_price'] - $v['price'] * 0.75);
                            $get_commission += ($commission * $v['count']);
                        }
                        $total_goods_count += $v['count'];
                        if ($v['ratio'] > 100) {
                            $commission = ($v['final_price'] - $v['price']) * (1 - 0.17)+$v['price']*0.25;
                            $get_commission += ($commission * $v['count']);
                        }
                    }
                    $commission_arr = array(
                        "order_id" => $insert_id,
                        "manager_id" => $mg['manager_id'],
                        "money" => $orders['money'],
                        "commission" => round($get_commission, 2),
                        "created_at" => date("Y-m-d H:i:s")
                    );
                    $this->db->insert("commission", $commission_arr);
                    if ($this->db->affected_rows()) {
                        $up_order = array(
                            "commission_total" => round($get_commission, 2),
                            "product_count" => $total_goods_count
                        );
                        $this->db->where(["order_bn" => $order_sn])->update("customer_order", $up_order);

                        // 下单推送 cj
                        $content = "您的客户" . $customer_name . "下单成功，订单总额：" . $order['order_money'] . "元";
                        $rr = $jpush->push($receiver = array('registration_id' => array($registration_id)), $title = $title_arr[0], $content, $extras = array(), $m_time = '86400');
                        $minfo['title'] = $title_arr[0];
                        $minfo['content'] = $content;
                        $minfo['type'] = '订单';
                        $minfo['target_id'] = $insert_id;
                        $minfo['have_read'] = '0';
                        $minfo['created_at'] = date("Y-m-d H:i:s");
                        $minfo['manager_id'] = $manager_id;
                        $this->db->insert("message", $minfo);
                        $history_info['name'] = $manager_name;
                        $history_info['tel'] = $manager_tel;
                        $history_info['error'] = $rr['status'] == 'fail' ? $rr['msg'] : "";
                        $history_info['content'] = $content;
                        $history_info['status'] = $rr['status'] == 'success' ? '成功' : '失败';
                        $history_info['created_at'] = date("Y-m-d H:i:s");
                        $this->db->insert("message_history", $history_info);
                    } else {
                        $data['msg'] .= ',佣金插入失败';
                    }
                }
            } elseif ($order_status == 11) {
                //下单信息
                $returns = json_decode($returns, true);
                if (!$returns || count($returns) <= 0) {
                    $data['status'] = "fail";
                    $data['msg'] = "退货信息不可为空";
                    $this->db->trans_rollback();
                    echo json_encode($data);
                    exit;
                }
                $order_up = [
                    'order_status' => $this->order_status($order_status),
                ];
                $this->db->where(["order_bn" => $order_sn])->update("customer_order", $order_up);
                if (!$this->db->affected_rows()) {
                    $data['status'] = "fail";
                    $data['msg'] = "同步失败";
                    $this->db->trans_rollback();
                    echo json_encode($data);
                    exit;
                } else {
                    $data['status'] = "success";
                    $data['msg'] = "同步成功";
                }
                // 退款时候减去业绩
                $order_info = $this->db->where(["order_bn" => $order_sn])->get("customer_order")->row_array();
                $money = floatval(-$returns['money']);
                $payment_date = $order_info['payment_date'];
                $date = $order_info['payment_date'] ? date("Y-m",strtotime($order_info['payment_date'])) : date("Y-m",time());
                find_all_father_id_month($this->db,$manager_id,$payment_date,$rr);
                // push_money表存入money
                $oinfo = $this->db->where(array("order_bn" => $order_sn))->get("customer_order")->row_array();
                if($oinfo)
                {
                    $oinfo = $this->db->where(array("order_bn" => $order_sn))->get("customer_order")->row_array();
                    $us = "update push_money set money=money".$money." where order_id = ".$oinfo['id'];
                    $rs = $this->db->query($us);
                    log_message('error','push_moeny修改退款，'.$order_sn.'，修改是否成功：'.$rs);
                }
                // 总业绩
                $rr[] = $manager_id;
                foreach ($rr as $v)
                {
                    $bl = $this->users_model->add_finish_norm($v,$date,$money);
                    if($bl)
                    {
                        // 推送上级业绩信息
                        $info = $this->users_model->get_one($v);
                        $p_res = $jpush->push($receiver = array('registration_id' => array($info['registration_id'])), $title = $title_arr[1], "辖下团队有客户退货，扣减业绩：".$money."元。", $extras = array(), $m_time = '86400');
                        // message表
                        $minfo['title'] = $title_arr[1];
                        $minfo['content'] = "辖下团队有客户退货，扣减业绩：".$money."元。";
                        $minfo['type'] = '业绩';
                        $minfo['target_id'] = $v;
                        $minfo['have_read'] = '0';
                        $minfo['created_at'] = date("Y-m-d H:i:s");
                        $minfo['manager_id'] = $manager_id;
                        $this->db->insert("message", $minfo);
                        // 推送历史纪录表
                        $history_info['name'] = $info['name'];
                        $history_info['tel'] = $info['tel'];
                        $history_info['error'] = $p_res['status'] == 'fail' ? $p_res['msg'] : "";
                        $history_info['content'] = $minfo['content'];
                        $history_info['status'] = $p_res['status'] == 'success' ? '成功' : '失败';
                        $history_info['created_at'] = date("Y-m-d H:i:s");
                        $this->db->insert("message_history", $history_info);
                    }
                }
                // 个人业绩 $my_performance
                $this->users_model->add_finish_norm($manager_id,$date,'','','','',$money);
                //如果存在父级，给父级的直招under_performance
                $sql = "select * from manager_bind_history where manager_id = " .$manager_id and "start_time <= '$payment_date' and end_time > '$payment_date'";
                $row = $this->db->query($sql)->row_array();
                if ($row){
                    $this->users_model->add_finish_norm($row['parent_id'],$date,0,0,0,0,0,$money);
                }

                //计算佣金
                $products = $returns['products'];
                //退货数量
                $total_goods_count = 0;
                if ($products && count($products) > 0) {
                    $return_commission = 0;
                    foreach ($products as $v) {
                        if ($v['ratio'] >= 75 && $v['ratio'] <= 100) {
                            $commission = ($v['final_price'] - $v['price'] * 0.75);
                            $return_commission += ($commission * $v['count']);
                        }
                        if ($v['ratio'] > 100) {
                            $commission = ($v['final_price'] - $v['price']) * (1 - 0.17) + $v['price']*0.25;;
                            $return_commission += ($commission * $v['count']);
                        }
                        $total_goods_count += $v['count'];
                    }
                    $commission_arr = array(
                        "order_id" => $order_info['id'],
                        "manager_id" => $order_info['manager_id'],
                        "money" => -round($returns['money'], 2),
                        "commission" => -round($return_commission, 2),
                        "created_at" => date("Y-m-d H:i:s")
                    );
                    $this->db->insert("commission", $commission_arr);
                    $insert_id1 = $this->db->insert_id();
                    if ($this->db->affected_rows()) {
                        $commission = $order_info['commission_total'] - $return_commission;
                        $up_arr = array(
                            "commission_total" => round($commission, 2),
                            "order_money" => round($order_info['order_money'] - $returns['money'], 2),
                            "product_count" => $order_info['product_count'] - $total_goods_count
                        );
                        $this->db->where(["order_bn" => $order_info['order_bn']])->update("customer_order", $up_arr);
                        // 退货推送 cj
                        $content = "您的客户" . $customer_name . "申请退货，退货商品金额为：" . $up_arr['order_money'] . "元，需退还佣金：" . round($return_commission, 2) . '元';
                        $rr = $jpush->push($receiver = array('registration_id' => array($registration_id)), $title = $title_arr[1], $content, $extras = array(), $m_time = '86400');
                        $minfo['title'] = $title_arr[1];
                        $minfo['content'] = $content;
                        $minfo['type'] = '订单';
                        $minfo['target_id'] = $order_info['id'];
                        $minfo['have_read'] = '0';
                        $minfo['created_at'] = date("Y-m-d H:i:s");
                        $minfo['manager_id'] = $manager_id;
                        $this->db->insert("message", $minfo);
                        $history_info['name'] = $manager_name;
                        $history_info['tel'] = $manager_tel;
                        $history_info['error'] = $rr['status'] == 'fail' ? $rr['msg'] : "";
                        $history_info['content'] = $content;
                        $history_info['status'] = $rr['status'] == 'success' ? '成功' : '失败';
                        $history_info['created_at'] = date("Y-m-d H:i:s");
                        $this->db->insert("message_history", $history_info);
                    } else {
                        $data['msg'] .= ',佣金插入失败';
                    }
                }
            } else {
                $order_up = [
                    'order_status' => $this->order_status($order_status),
                ];
                if ($order_status == 1) {
                    // 入账时候新增计算业绩
                    $sql = "select * from customer_order where order_bn =".$order_sn;
                    $order_info = $this->db->query($sql)->row_array();
                    $money = $order_info['order_money'];
                    find_all_father_id($this->db,$manager_id,$rr);
                    // 总业绩
                    $rr[] = $manager_id;
//                    $date = date("Y-m",time());
                    $date = date("Y-m",strtotime($time));
                    foreach ($rr as $v)
                    {
                        $bl = $this->users_model->add_finish_norm($v,$date,$money);
                        if($bl)
                        {
                            // 推送上级业绩信息
                            $info = $this->users_model->get_one($v);
                            $p_res = $jpush->push($receiver = array('registration_id' => array($info['registration_id'])), $title = $title_arr[2], "辖下团队有客户成功付款，增加业绩：".$money."元。", $extras = array(), $m_time = '86400');
                            // message表
                            $minfo['title'] = $title_arr[2];
                            $minfo['content'] = "辖下团队有客户成功付款，增加业绩：".$money."元。";
                            $minfo['type'] = '业绩';
                            $minfo['target_id'] = $v;
                            $minfo['have_read'] = '0';
                            $minfo['created_at'] = date("Y-m-d H:i:s");
                            $minfo['manager_id'] = $manager_id;
                            $this->db->insert("message", $minfo);
                            // 推送历史纪录表
                            $history_info['name'] = $info['name'];
                            $history_info['tel'] = $info['tel'];
                            $history_info['error'] = $p_res['status'] == 'fail' ? $p_res['msg'] : "";
                            $history_info['content'] = $minfo['content'];
                            $history_info['status'] = $p_res['status'] == 'success' ? '成功' : '失败';
                            $history_info['created_at'] = date("Y-m-d H:i:s");
                            $this->db->insert("message_history", $history_info);
                            // push_money表存入money
                            $oinfo = $this->db->where(array("order_bn" => $order_sn))->get("customer_order")->row_array();
                            if($oinfo)
                            {
                                if($v == $manager_id)
                                {
                                    // 没有上级ID
                                    $v = null;
                                }
                                $this->db->insert("push_money", array('manager_id'=>$manager_id,'money'=>$money,'push_money'=>0,'status'=>'未结算','created_at'=>$time,'order_id'=>$oinfo['id'],'parent_id'=>$v));
                            }

                        }
                    }
                    // 个人业绩 $my_performance
                    $this->users_model->add_finish_norm($manager_id,$date,'','','','',$money);
                    //如果存在父级，给父级的直招under_performance
                    $sql = "select * from manager_bind where manager_id = " .$manager_id ;
                    $row = $this->db->query($sql)->row_array();
                    if ($row){
                        $this->users_model->add_finish_norm($row['parent_id'],$date,0,0,0,0,0,$money);
                    }
                    $order_up['payment_date'] = $time;
                    $order_up['commission_status'] = "已入账";
                }
                if ($order_status == 3) {
                    $order_up['completed_date'] = $time;
                }
                $this->db->where(["order_bn" => $order_sn])->update("customer_order", $order_up);
                if (!$this->db->affected_rows()) {
                    $data['status'] = "fail";
                    $data['msg'] = "同步失败";
                    $this->db->trans_rollback();
                    echo json_encode($data);
                    exit;
                } else {
                    $data['status'] = "success";
                    $data['msg'] = "同步成功";
                    if ($order_status == 1) {
                        // 付款推送 cj
                        // 订单信息
                        $order_info = $this->db->where(["order_bn" => $order_sn])->get("customer_order")->row_array();
                        $content = "您的客户" . $customer_name . "已付款，付款总额：" . $order_info['order_money'] . "元，佣金：" . $order_info['commission_total'] . '元，预计15天后到账';
                        $rr = $jpush->push($receiver = array('registration_id' => array($registration_id)), $title = $title_arr[2], $content, $extras = array(), $m_time = '86400');
                        $minfo['title'] = $title_arr[2];
                        $minfo['content'] = $content;
                        $minfo['type'] = '订单';
                        $minfo['target_id'] = $order_info['id'];
                        $minfo['have_read'] = '0';
                        $minfo['created_at'] = date("Y-m-d H:i:s");
                        $minfo['manager_id'] = $manager_id;
                        $this->db->insert("message", $minfo);
                        $history_info['name'] = $manager_name;
                        $history_info['tel'] = $manager_tel;
                        $history_info['error'] = $rr['status'] == 'fail' ? $rr['msg'] : "";
                        $history_info['content'] = $content;
                        $history_info['status'] = $rr['status'] == 'success' ? '成功' : '失败';
                        $history_info['created_at'] = date("Y-m-d H:i:s");
                        $this->db->insert("message_history", $history_info);
                    }
                }
            }
            $this->db->trans_commit();
        } else {
            $data['msg'] = "参数错误";
            $data['status'] = "fail";
            $data['data'] = "";
        }
        return $data;
    }

    function order_status($status = 0)
    {
        $arr = array(
            "0" => "等待买家付款",
            "1" => "买家已付款",
            "2" => "卖家已发货",
            "3" => "交易成功",
            "8" => "交易结束",
            "9" => "关闭交易",
            "10" => "退货中",
            "11" => "已退货"
        );
        return $arr[$status];
    }
}